package demo;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Demo01 {
    public static void main(String[] args) {
        /*
         * 比较 ArrayList 和 LinkedList的各种性能
         */
        //准备10万个元素的ArrayList
        ArrayList<Integer> arrayList = new ArrayList<>();
        LinkedList<Integer> linkedList = new LinkedList<>();
        Integer[] array = new Integer[100000];
        for(int i=0; i<100000; i++){
            arrayList.add(i);
            linkedList.add(i);
        }
        //测试从数组中获取(随机访问)元素的性能,ArrayList 和 Array 读取性能相当
        long t1 = System.nanoTime();
        Integer n = array[0];
        long t2 = System.nanoTime();
        n = array[array.length-1];
        long t3 = System.nanoTime();
        n = array[array.length/2];
        long t4 = System.nanoTime();
        System.out.println("Array:[0]"+(t2-t1));
        System.out.println("Array:[length-1]"+(t3-t2));
        System.out.println("Array:[length/2]"+(t4-t3));

        test(arrayList);
        test(linkedList);

    }
    public static void test(List<Integer> list){
        //利用反射API动态获取一个类的名字
        String className = list.getClass().getName();
        //System: 系统， current：当前的  Time时间， millis毫秒
        // System.currentTimeMillis() 获取时间毫秒数
        // nano: 纳秒， 1毫秒=1000000纳秒， 一百万纳秒
        //测试 头部插入性能 和 尾部插入性能
        Integer n = 999;
        long t1 = System.nanoTime();
        list.add(0, n);
        long t2 = System.nanoTime();
        list.add(list.size()-1, n);
        long t3 = System.nanoTime();
        list.add(list.size()/2,n);
        long t4 = System.nanoTime();
        System.out.println(className+" add(0,999)："+(t2-t1));
        System.out.println(className+" add(size-1,999)："+(t3-t2));
        System.out.println(className+" add(size/2,999)："+(t4-t3));

        t1 = System.nanoTime();
        Integer e = list.get(2);
        t2 = System.nanoTime();
        e = list.get(list.size()-1);
        t3 = System.nanoTime();
        e = list.get(list.size()/2);
        t4 = System.nanoTime();
        System.out.println(className+" get(0)："+(t2-t1));
        System.out.println(className+" get(size-1)："+(t3-t2));
        System.out.println(className+" get(size/2)："+(t4-t3));

        t1 = System.nanoTime();
        e = list.set(2, n);
        t2 = System.nanoTime();
        e = list.set(list.size()-1, n);
        t3 = System.nanoTime();
        e = list.set(list.size()/2, n);
        t4 = System.nanoTime();
        System.out.println(className+" set(0,n)："+(t2-t1));
        System.out.println(className+" set(size-1,n)："+(t3-t2));
        System.out.println(className+" set(size/2,n)："+(t4-t3));

    }
}
